package com.cslg.ac.demo.controller.sign;

import com.cslg.ac.demo.constant.ResponseCode;
import com.cslg.ac.demo.entity.user.User;
import com.cslg.ac.demo.service.sign.SignService;
import com.cslg.ac.demo.util.communicate.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Controller
public class SignController {
    @Autowired
    SignService signService;

    @RequestMapping(value = "/sign/signToday",method = RequestMethod.POST)
    public void signToday(@RequestParam Integer id,PrintWriter out){
        if(id == null){
            ResponseUtil.responseCode(out,ResponseCode.PARAM_ILLEGAL);
            return;
        }
        int code;
        try {
            code = signService.SignToday(id);
        } catch (Exception e) {
            e.printStackTrace();
            ResponseUtil.responseCode(out,ResponseCode.SERVER_ERROR);
            return;
        }
        ResponseUtil.responseCode(out,code);
    }

    /**
     * 获取连续签到天数
     * @param id
     */
    @RequestMapping(value = "/sign/getSignDay",method = RequestMethod.POST)
    public void getSignDay(@RequestParam Integer id, PrintWriter out){
        if(id == null){
            ResponseUtil.responseCode(out,ResponseCode.PARAM_ILLEGAL);
            return;
        }
        Integer day;
        try {
            day = signService.getSignDay(id);
        } catch (Exception e) {
            e.printStackTrace();
            ResponseUtil.responseCode(out,ResponseCode.SERVER_ERROR);
            return;
        }
        Map<String,Object> param = new HashMap<>();
        param.put("day",day);
        if(day == null){
            param.put("day",0);
        }
        ResponseUtil.response(out,ResponseCode.REQUEST_SUCCESSED,param);


    }

    @RequestMapping(value = "/sign/sign",method = RequestMethod.POST)
    public void sign(HttpSession session, PrintWriter out){
        User user = (User)session.getAttribute("user");
        int code = -1;
        try {
            code = signService.sign(user.getId());
        }catch (Exception e){
            e.printStackTrace();
            ResponseUtil.responseCode(out,ResponseCode.SERVER_ERROR);
            return;
        }
        ResponseUtil.responseCode(out,code);

    }

}
